import click
from watchlist import app, db
from watchlist.models import User, Movie


@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
    """Initialize the database"""
    if drop:
        db.drop_all()
    db.create_all()
    click.echo("Initialized database.")


@app.cli.command()
@click.option('--count', default=20, help='生成电影数据,默认20条')
def forge(count):
    """Generate fake data."""
    from faker import Faker
    db.drop_all()
    db.create_all()

    # 全局的两个变量移动到这个函数内
    fake = Faker('zh_CN')
    click.echo('Working')
    for i in range(count):
        movie = Movie(
            title=fake.name(),
            year=fake.year(),
            timestamp=fake.date_time_this_year()
        )
        db.session.add(movie)
    name = 'Zhou Chuang'
    user = User(name=name)
    db.session.add(user)
    db.session.commit()
    click.echo('一共生成%d条数据.' % count)


@app.cli.command()
@click.option('--username', prompt=True, help='The username used to login')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password userd to login')
def admin(username, password):
    """Create user."""
    db.create_all()
    user = User.query.first()
    if user is not None:
        click.echo('Updating user ...')
        user.username = username
        user.set_password(password)  # 设置密码
    else:
        click.echo('Create user ...')
        user = User(username=username, name='Admin')
        user.set_password(password)  # 设置密码
        db.session.add(user)

    db.session.commit()  # 提交数据库会话
    click.echo("Done.")